#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Created on 2011/03/31

@author: Rafael
'''
import os
import csv
from unicodedata import normalize

class WriteInfo():
    
    #create and write the information in the csv file
    def escrita_csv(self, ano, dados):
        '''
        escrita dos dados em ficheiro csv
        '''
        file = 'csv/200{0}.csv'.format(ano)
        try:
            os.stat(os.path.dirname(file))
            pass
        except:
            os.mkdir(os.path.dirname(file))
            pass
        ficheiro = open(file,"wb")
        csvwriter = csv.writer( ficheiro, delimiter=',')
        for dado in dados:
            if(os.name == "posix"):
                data = []
                for item in dado:
                    data.append(item.encode('utf-8'))
                    pass
                csvwriter.writerow(data)
                pass
            else:
                csvwriter.writerow(dado)
            pass
        ficheiro.close()
        pass
    
    #create the website in html
    def createHtml(self, ano, nDocentes, listTipo, nInst, nGraus, 
                    nDocenteTipo, listInstPerTipo, nInstPerTipo, nDocenteGrausTipo, nGrausTipo,
                                teacherPerDegreePerInst,teachersPerInst, nTeachersPerInst, listInst):
        try:
            os.stat('html')
            pass
        except:
            os.mkdir('html')
            pass
        file = 'html/200{0}/index.html'.format(ano)
        try:
            os.stat(os.path.dirname(file))
            pass
        except:
            os.mkdir(os.path.dirname(file))
            pass
        
        self.indexAno(ano, nDocentes, listTipo, nInst, nGraus)
        self.tiposHTML(ano, listTipo, nDocenteTipo, listInstPerTipo, nInstPerTipo
                       , nDocenteGrausTipo, nGrausTipo)
        self.listDocenteInst(ano, teacherPerDegreePerInst,teachersPerInst,listInst, nTeachersPerInst)
        pass
    
    #create the index pages per year
    def indexAno(self,ano, nDocentes, listTipo, nInst, nGraus):
        ficheiro = open("html/200{0}/index.html".format(ano), "w")
        header = ("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                        <html xmlns="http://www.w3.org/1999/xhtml"><head>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <title>Ano 2000</title>
                        </head>
                        <body>""")
        body = """<table width="600" border="0" align="center">
                <tr>
                <td><h1>Ano 200{0}</h1></td>
                </tr>
                <tr>
                <td><h3>Nº Total de Tipos de Instituições - {1}</h3></td>
                </tr>
                <tr>
                <td><h3>Nº Total de Instituições - {2}</h3></td>
                </tr>
                <tr>
                <td><h3>Nº Total de Docentes - {3}</h3></td>
                </tr>
                <tr>
                <td><h3><a href="NGrauAno.html">Nº de Docentes por Grau</a></h3></td>
                </tr>
                <tr>
                <td><h2>Tipos de Instituições</h2></td>
                </tr>
                """.format(ano, len(listTipo), nInst[0], nDocentes)
                    
        for inst in listTipo:
            instutf8 = inst[0].encode('utf-8')
            body += """<tr>
                        <td><a href="{0}.html">{1}</a></td>
                        </tr>""".format(normalize('NFKD', instutf8.decode('utf-8')).encode('ASCII','ignore'),instutf8)
            pass
        
        body += """</table>"""
        
        footer = """</body></html>"""
        
        html = header + body + footer
        
        ficheiro.write(html)

        ficheiro.close()
        
        #coloca os graus no dicionario
        nGrau = {}
        for row in nGraus:
            nGrau[row[0]] = row[1]
            pass
        
        self.nDocentesGrau(ano, nGrau, "html/200{0}/NGrauAno.html".format(ano))
        pass
    
    #create the pages of the type of institutions
    def tiposHTML(self, ano, listTipo, nDocenteTipo, listInstPerTipo,nInstPerTipo, 
                  nDocenteGrausTipo, nGrausTipo):
        i = 0
        lenT = 0
        flag = 0
        for tipo in listTipo:
            tipo_utf8 = tipo[0].encode('utf-8')
            ficheiro = open("html/200{0}/{1}.html".format(ano,normalize('NFKD', tipo_utf8.decode('utf-8')).encode('ASCII','ignore')), "w")
            header = ("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                        <html xmlns="http://www.w3.org/1999/xhtml"><head>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <title>{0}</title>
                        </head>
                        <body>""".format(tipo_utf8))
            
            body = """<table width="600" border="0" align="center">
                <tr>
                <td><h1>Ano 200{0}</h1></td>
                </tr>
                <tr>
                <td><h3>Nº Total de Docentes - {1}</h3></td>
                </tr>
                <tr>
                <td><h3>Nº Total de Instituições - {2}</h3></td>
                </tr>
                <tr>
                <td><h3><a href="NGrauTipo{3}.html">Nº de Docentes por Grau</a></h3></td>
                </tr>
                <tr>
                <td><h3>Lista de Instituições</h3></td>
                </tr>""".format(ano, nDocenteTipo[i][1], nInstPerTipo[i][1],normalize('NFKD', tipo_utf8.decode('utf-8')).encode('ASCII','ignore'))
            
            for j in range(lenT,nInstPerTipo[i][1]+lenT):
                listInstPerTipo_utf8 = listInstPerTipo[j][1].encode('utf-8')
                body += """<tr>
                        <td><a href="instituicoes/{0}.html">{1}</a></td>
                        </tr>""".format(normalize('NFKD', listInstPerTipo_utf8.decode('utf-8')).encode('ASCII','ignore'),listInstPerTipo_utf8)
                pass
            
            lenT = lenT + nInstPerTipo[i][1]
            
            body += """</table>"""
        
            footer = """</body></html>"""
        
            html = header + body + footer
            
            ficheiro.write(html)
            ficheiro.close()
            
            #coloca os graus no dicionario
            nGrauDocente = {}
            for j in range(flag,nGrausTipo[i][1]+flag):
                nGrauDocente[nDocenteGrausTipo[j][1]] = nDocenteGrausTipo[j][2]
                pass
            flag = nGrausTipo[i][1]+flag
            
            #cria o nome do ficheiro
            nome = "html/200{0}/NGrauTipo{1}.html".format(ano, normalize('NFKD', tipo_utf8.decode('utf-8')).encode('ASCII','ignore'))
            
            #cria o html com os graus
            self.nDocentesGrau(ano, nGrauDocente, nome)
            i = i + 1
            pass
                
        pass
    
    #create the pages per institutions
    def listDocenteInst(self,ano, teacherPerDegreePerInst,teachersPerInst,listInst, nTeachersPerInst):
        try:
            os.stat('html/200{0}/instituicoes'.format(ano))
            pass
        except:
            os.mkdir('html/200{0}/instituicoes'.format(ano))
            pass
        i = 0
        lenT = 0
        for inst in listInst:
            inst_utf8 = inst[0].encode('utf-8')
            try:
                ficheiro = open("html/200{0}/instituicoes/{1}.html".format(ano,normalize('NFKD', inst_utf8.decode('utf-8')).encode('ASCII','ignore')), "w")
                pass
            except:
                ficheiro = open("html/200{0}/instituicoes/{1}.html".format(ano,normalize('NFKD', (inst_utf8.replace("/","")).decode('utf-8')).encode('ASCII','ignore')), "w")
                pass
                
            header = ("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                        <html xmlns="http://www.w3.org/1999/xhtml"><head>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <title>{0}</title>
                        </head>
                        <body>""".format(inst_utf8))
            
            body = """<table width="600" border="0" align="center">
                <tr>
                <td><h1>Ano 200{0}</h1></td>
                </tr>
                <tr>
                <td><h3>Nº Total de Docentes - {1}</h3></td>
                </tr>
                <tr>
                <td><h3><a href="NGrauTipo{2}.html">Nº de Docentes por Grau</a></h3></td>
                </tr>
                <tr>
                <td><h3>{3}</h3></td>
                </tr>""".format(ano, nTeachersPerInst[i][1], normalize('NFKD', inst_utf8.decode('utf-8')).encode('ASCII','ignore'), inst_utf8)    
            
            for j in range(lenT,nTeachersPerInst[i][1]+lenT):
                body += """<tr>
                        <td>{0}</td>
                        </tr>""".format(teachersPerInst[j][1].encode('utf-8'))
                pass
            lenT = lenT + nTeachersPerInst[i][1]
            
            body += """</table>"""
        
            footer = """</body></html>"""
        
            html = header + body + footer
            
            ficheiro.write(html)
            ficheiro.close()
            
            #cria o nome do ficheiro
            nome = "html/200{0}/instituicoes/NGrauTipo{1}.html".format(ano, normalize('NFKD', (inst_utf8.replace("/","")).decode('utf-8')).encode('ASCII','ignore'))
            
            #cria o html com os graus
            self.nDocentesGrau(ano, teacherPerDegreePerInst[inst[0]], nome)
            i = i + 1
            
            pass
        pass
    
    #create the pages with the  teachers per degree
    def nDocentesGrau(self, ano, nGraus, nome):
        ficheiro = open("{0}".format(normalize('NFKD', nome.decode('utf-8')).encode('ASCII','ignore')), "w")
        header = ("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                        <html xmlns="http://www.w3.org/1999/xhtml"><head>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <title>Ano 2000</title>
                        </head>
                        <body>""")
        body = """<table width="600" border="0" align="center">
                <tr>
                <td><h1>Ano 200{0}</h1></td>
                </tr>
                <tr>
                <td><h2>Nº de Docentes por Grau</h2></td>
                </tr>
                """.format(ano)
                
        for grau,nDocente in nGraus.iteritems():
            body += """<tr>
                    <td>{0} - {1}</td>
                    </tr>""".format(grau.encode('utf-8'),nDocente)
            pass
        
        body += """</table>"""
        
        footer = """</body></html>"""
        
        html = header + body + footer
        
        ficheiro.write(html)

        ficheiro.close()
        pass
    
    #create the index page
    def doIndex(self):
        ficheiro = open('index.html', "w")
        
        header = ("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                        <html xmlns="http://www.w3.org/1999/xhtml"><head>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <title>Rebides</title>
                        </head>
                        <body>""")
        body = """<table width="600" border="0" align="center">
                <tr>
                <td><h1>Rebides</h1></td>
                </tr>
                """
        for i in range(0,10):
            try:
                os.stat('html/200{0}'.format(i))
                body += """<tr>
                        <td><a href="html/200{0}/"><h3>Ano 200{0}</h3></a></td>
                        </tr>""".format(i)
                pass
            except:
                continue
                pass
            pass
        
        body += """</table>"""
        
        footer = """</body></html>"""
        
        html = header + body + footer
        
        ficheiro.write(html)

        ficheiro.close()
        
        pass
    
    pass